
import { onMounted, onUnmounted } from 'vue';

export const selectUniqueRandom = <T>(array: T[], count: number): T[] => {
    const selectedIndices = new Set<number>();
    const selectedElements: T[] = [];

    while (selectedIndices.size < count) {
        const randomIndex = Math.floor(Math.random() * array.length);
        if (!selectedIndices.has(randomIndex)) {
            selectedIndices.add(randomIndex);
            selectedElements.push(array[randomIndex]);
        }
    }

    return selectedElements;
};

export const useIntersectionObserver = <T extends Element>(callback: (entries: IntersectionObserverEntry[]) => void) => {
    let observer: IntersectionObserver | null = null;

    const startObserving = (elements: T[]) => {
        if (observer) {
            elements.forEach((element) => {
                observer?.observe(element);
            });
        }
    };

    const stopObserving = (elements: T[]) => {
        if (observer) {
            elements.forEach((element) => {
                observer?.unobserve(element);
            });
        }
    };

    onMounted(() => {
        observer = new IntersectionObserver(callback);
    });

    onUnmounted(() => {
        if (observer) {
            observer.disconnect();
        }
    });

    return {
        startObserving,
        stopObserving,
    };
};